<?php
class Helper_BSS_Array
{
	/**
	 * 搜索二维数组
	 * @param $haystack 传入数组
	 * @param $key 第二层数组key
	 * @param $value 第二层数组value
	 * @return 找到的第二层数组
	 */
	static function Search($haystack, $key, $value)
	{
		$ret = array();
		foreach ($haystack as $h)
		{
			if ($h[$key] == $value)
			{
				$ret[] = $h;
			}
		}
		return $ret;
	}
	
	static function getTree($items)
	{
		 foreach ($items as $item)
	        $items[$item['pid']]['children'][$item['id']] = &$items[$item['id']];
	    return isset($items[0]['children']) ? $items[0]['children'] : array();
	}
	
	static function SortByValue($arr, $key, $sort='asc')
	{
		$new_key = array();
		foreach ($arr as $k => $a)
		{
			$new_key[$k] = $a[$key];
		}
		if ($sort == 'asc')
		{
			asort($new_key);
		}
		if ($sort == 'desc')
		{
			arsort($new_key);
		}
		$ret = array();
		foreach ($new_key as $k => $n)
		{
			$ret[] = $arr[$k];
		}
		return $ret;
	}

	/**
	 * 获取捆绑item表产品的数据
	 * @param $post 提交的item数据
	 */
	static function getProductBindItemToArray($post)
	{
		$key_arr = array();
		$item_arr =array();
		foreach ($post as $key => $value)
		{
			if (substr($key,0,11) == 'product_id_')
			{
				$key_arr[] = substr($key,11,strlen($key)-11);
			}
		}
		foreach ($key_arr as $k)
		{
			$temp = array();
			$temp['product_basic_id'] = $post['product_id_' . $k];
			$temp['quantity'] = intval($post['product_quantity_' . $k]);
			$item_arr[$k] = $temp;
		}
		return $item_arr;
	}
	
	/*
	* 在二维数组获取键值为$key的元素，并组装成新的数组
	* $param $array 二维数组
	* $param $key 需要从二维数组中获取元素的键值
	*/
	static function getDistinctValueToArrayByKey($array, $key)
	{
		$new = array();
		foreach ($array as $a)
		{
			$new[] = $a[$key];
		}
		return array_unique($new);
	}
	
	/*
	* 在生成分页数组
	* $param $num 数据条数
	* $param $cp 当前页
	* $param $ps 页条数
	*/
	static function PageArray($num, $cp, $ps)
	{
		$page_set = array();
		$page_count = abs(intval(ceil($num/$ps)));
		$page_set['record_count'] = $num;
		$page_set['page_count'] = $page_count;
		$page_set['first'] = 1;
		$page_set['last'] = $page_count;
		if ($cp>=$page_count)
		{
			$page_set['next'] = $cp;
		}
		else 
		{
			$page_set['next'] = intval($cp+1);
		}
		if ($cp>0)
		{
			if (abs($cp)==1)
			{
				$page_set['prev'] = 1;
			}
			else 
			{
				$page_set['prev'] = abs($cp)-1;
			}
		}
		else 
		{
			$page_set['prev'] = 1;
		}
		$page_set['current'] = $cp;
		$page_set['page_size'] = $ps;
		$page_set['page_base'] = 1;
		
		return $page_set;
	}
}